package com.example.demo.controller;

import com.example.demo.config.AjaxResult;
import com.example.demo.model.UserInfo;
import com.example.demo.service.UserService;
import com.example.demo.util.ConstVariable;
import com.example.demo.util.PasswordUtil;
import com.google.code.kaptcha.Constants;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/reg")
    public Object reg(HttpServletRequest request, String username, String password1, String password2, String captcha) {
        // 参数输入错误处理
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password1) || !StringUtils.hasLength(password2)) {
            return AjaxResult.fail(-1, "参数输入错误");
        }

        HttpSession session = request.getSession();
        String savedCaptcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);

        // 验证码错误处理
        if (savedCaptcha == null || !savedCaptcha.equalsIgnoreCase(captcha)) {
            return AjaxResult.fail(-1, "验证码错误，注册失败");
        }

        // 密码不一致检查
        if (!password1.equals(password2)) {
            return AjaxResult.fail(-1, "前后密码不一致");
        }

        // 注册用户
        try {
            int result = userService.reg(username, PasswordUtil.encrypt(password1));
            if (result != 1) {
                return AjaxResult.fail(-1, "注册失败，用户名已存在");
            }
        } catch (DataAccessException e) {
            // 检查异常信息是否包含“Duplicate entry”来判断用户名是否已存在
            if (e.getMessage().contains("Duplicate entry")) {
                return AjaxResult.fail(-1, "用户名已存在，请更换用户名");
            } else {
                return AjaxResult.fail(-1, "注册过程中发生错误: " + e.getMessage());
            }
        } catch (Exception e) {
            return AjaxResult.fail(-1, "注册过程中发生错误: " + e.getMessage());
        }



        return AjaxResult.success("注册成功", "1");
    }


    @RequestMapping("/login")
    public Object login(HttpServletRequest request, String username, String password, String captcha) {

        if (!StringUtils.hasLength(username) ||!StringUtils.hasLength(password) ||!StringUtils.hasLength(captcha)) {
            return AjaxResult.fail(-1, "参数输入错误,登录失败");
        }

        // 从 session 中获取保存的验证码
        HttpSession session = request.getSession();
        String savedCaptcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);

        if (savedCaptcha == null ||!savedCaptcha.equalsIgnoreCase(captcha)) {
            return AjaxResult.fail(-1, "验证码错误，登录失败");
        }

        UserInfo userInfo = userService.selectByUsername(username);
        // 随机加盐算法，未加密的密码用同样的加密算法和数据库中的加密算法进行比较
        if (userInfo == null ||!PasswordUtil.decrypt(password, userInfo.getPassword()) || userInfo.getId() <= 0) {
            return AjaxResult.fail(-1, "账号或密码错误，登录失败");
        }

        session.setAttribute(ConstVariable.USER_SESSION_KEY, userInfo);
        return AjaxResult.success("登录成功", 1);
    }
    /**
     * 获取当前登录的用户名
     */
    @RequestMapping("/get-user")
    public Object getUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return AjaxResult.fail(401, "当前用户未登录");
        }
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail(401, "当前用户未登录");
        }
        return AjaxResult.success(userInfo); // 这里我们可以直接用AjaxResult自定义统一格式返回，也可以传统的统一格式返回
    }

    @SneakyThrows
    @RequestMapping("/logout")
    public Object logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(ConstVariable.USER_SESSION_KEY) == null) {
            //response.sendRedirect("/login.html"); // 当前用户未登录
            return AjaxResult.fail(401, "当前用户未登录！");
        }
        session.setAttribute(ConstVariable.USER_SESSION_KEY, null);
        //response.sendRedirect("/login.html");
        return AjaxResult.success("当前状态正常，可以正常退出！", "true");
    }

    @RequestMapping("/get-address")
    public Object getAddress(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return AjaxResult.fail(401, "当前用户未登录");
        }
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        int uid = userInfo.getId();
        System.out.println(uid);
        if (uid <= 0) {
            return AjaxResult.fail(401, "当前用户未登录");
        }
        return AjaxResult.success("获取收货地址成功", userService.getAddress(uid));
    }

    @RequestMapping("/get-userinfo")
    public Object addAddress(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return AjaxResult.fail(401, "当前用户未登录");
        }
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        int uid = userInfo.getId();
        System.out.println(uid);
        if (uid <= 0) {
            return AjaxResult.fail(401, "当前用户未登录");
        }
        return AjaxResult.success("获取用户信息成功", userService.getUserInfo(uid));
    }

    @RequestMapping("/change-password")
    public Object changePassword(HttpServletRequest request, String oldPassword, String newPassword1, String newPassword2) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return AjaxResult.fail(401, "当前用户未登录");
        }
        if (!newPassword1.equals(newPassword2)) {
            return AjaxResult.fail(-1, "前后密码不一致");
        }
        if (oldPassword.length() < 6 || newPassword1.length() < 6) {
            return AjaxResult.fail(-1, "密码长度不能少于6位");
        }
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        int uid = userInfo.getId();
        String username = userInfo.getUsername();
        UserInfo userInfo2 = userService.selectByUsername(username);
        // 随机加盐算法，未加密的密码用同样的加密算法和数据库中的加密算法进行比较
        if (userInfo == null || !PasswordUtil.decrypt(oldPassword, userInfo2.getPassword()) || userInfo.getId() <= 0) {
            return AjaxResult.fail(-1, "密码错误，更新失败");
        } else {
            int result = userService.changePassword(PasswordUtil.encrypt(newPassword1), uid);
            if (result != 1) {
                return AjaxResult.fail(-1, "原密码不正确");
            } else {
                return AjaxResult.success("更新用户信息成功", "1");
            }
        }
    }

    @RequestMapping("/change-userinfo")
    public Object changeUserInfo(HttpServletRequest request, String email, String phone, String address) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return AjaxResult.fail(401, "当前用户未登录");
        }
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        int uid = userInfo.getId();
        UserInfo userinfo = new UserInfo();
        userinfo.setId(uid);
        userinfo.setEmail(email);
        userinfo.setPhone(phone);
        userinfo.setAddress(address);
        return AjaxResult.success("更新用户信息成功", userService.changeUserInfo(userinfo));}


}
